from django.shortcuts import render

from rest_framework.generics import RetrieveUpdateAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.answer.models import Label
from apps.mycenter.serializer import UserCenterSerializer, UpdatePasswordSerializer, UpdateLabelSerializer


# 用户信息及修改
from apps.users.models import User


class UserCenterView(RetrieveUpdateAPIView):
    '''GET  PUT  /user/'''

    serializer_class = UserCenterSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        user = self.request.user
        # # 一查多
        # replies = user.replies.all()
        # user.answer_question = []
        # for i in replies:
        #     if i.type == 2:
        #         user.answer_question.append(i)

        return user


# 修改密码
class UpdatePasswordView(UpdateAPIView):

    permission_classes = [IsAuthenticated]
    serializer_class = UpdatePasswordSerializer

    def get_object(self):

        return self.request.user


# 修改擅长技术
class UpdateLabelView(UpdateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = UpdateLabelSerializer

    def get_object(self):

        return self.request.user


# 关注与取消
class AttentionView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request, id):
        user = request.user
        idols = user.idols.all()
        try:
            new_user = User.objects.get(id=id)
        except User.DoesNotExist:
            return Response({'success': False, 'message': '用户不存在'})
        if new_user in idols:
            return Response({'success': False, 'message': '反复关注'})
        else:
            user.idols.add(new_user)

        return Response({'seccess': True, 'message': '关注成功'})

    def delete(self, request, id):
        try:
            new_user = User.objects.get(id=id)
        except User.DoesNotExist:
            return Response({'success': False, 'message': '用户不存在'})
        user = request.user
        idols = user.idols.all()
        if new_user in idols:
            user.idols.remove(new_user)
        else:
            return  Response({'seccess': False, 'message': '未关注'})

        return Response({'seccess': True, 'message': '取消关注成功'})
